package com.woniu.shiroConfig;

import com.woniu.entity.EverEmp;
import com.woniu.entity.EverRole;
import com.woniu.service.IEverEmpService;
import com.woniu.service.IEverEmproleService;
import com.woniu.service.IEverRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class EmpRealm extends AuthorizingRealm {
    @Autowired
    IEverEmpService empService;
    @Autowired
    IEverEmproleService erService;
    @Autowired
    IEverRoleService roleService;
    @Override
    /*
    * 授权
    * */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("2222222222222222222222222222");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //数据库设置权限
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal();
        System.out.println(primaryPrincipal);
        Subject subject = SecurityUtils.getSubject();
         EverEmp currentEmp= (EverEmp)subject.getPrincipal();
            //（）里填写该用户的权限 通过连表查询
        Set<String> roles=new HashSet<>();

        EverRole everRole = roleService.findEmpAllRoles(erService.findEmpAllRidByAccount(currentEmp));

                roles.add(everRole.getRname());
        System.out.println(roles+"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
                info.setRoles(roles);

//         info.addStringPermission("/");
        return info;
    }

    @Override

    /*
     * 认证
     * */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
                //在此次连接数据库，并将用户在数据空中查找
        UsernamePasswordToken empToken=(UsernamePasswordToken) token;
        System.out.println("11111111111111111111111");
        EverEmp emp = empService.findLoginByAccount(empToken.getUsername());
        if(emp==null){
            //抛出异常UnknownAccountException
            return null;
        }


        return new SimpleAuthenticationInfo(emp, emp.getEpwd(), "");
    }
}
